﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Planlama
{
    public partial class Uretilen : XForm
    {
        public Uretilen()
        {
            InitializeComponent();
        }

        int DagilimId;
        BindingSource bsOrders;
        private void Uretilen_Load(object sender, EventArgs e)
        {

            bsOrders = gridView1.Init("GetUretilen");
            //gridView1.Columns["Sezon"].ColumnEdit = RI(Rp.Sezon);
            gridView1.FormatAsNumber(0, "Toplam");
            gridView1.AddSummary("Toplam");
            for (int i = 1; i < 29; i++)
                gridView1.AddSummary(String.Format("A{0}", i.ToString().PadLeft(2, '0')));

            gridView1.RowCellStyle += new RowCellStyleEventHandler(gv_RowCellStyle);
            RepositoryItemGridLookUpEdit riDagilim = (gridView1.Columns["DagilimId"].ColumnEdit as RepositoryItemGridLookUpEdit);
            riDagilim.Closed += new DevExpress.XtraEditors.Controls.ClosedEventHandler(Orders_Closed);

            DagilimId = intParse(bsOrders, "DagilimId");
            bsOrders.CurrentChanged += bs_CurrentChanged;
            DagilimChanged();

            gridView1.BestFitColumns();

            btnOku.ItemClick += btnOku_ItemClick;
        }

        void btnOku_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string str = string.Empty;
            foreach (int rowhandle in gridView1.GetSelectedRows())
                str += gridView1.GetRowCellDisplayText(rowhandle, "idx") + ",";
            if (str.Length > 1)
                str = str.Substring(0, str.Length - 1);

            ds.Clear();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                if (openFileDialog1.OpenFile() != null)
                {
                    DataTable dt = ReadExcel(openFileDialog1.FileName);
                    if (dt != null)
                    {
                        //TODO: sıra çok önemli!
                        dt.Columns[0].ColumnName = "Barkod";
                        dt.Columns[1].ColumnName = "Model";
                        dt.Columns[2].ColumnName = "Art";
                        dt.Columns[3].ColumnName = "Taglia";
                        if (dt.Columns.Count > 5)
                            dt.Columns.RemoveAt(5);
                        if (dt.Columns.Count > 4)
                            dt.Columns.RemoveAt(4);

                        gridView2.Init("EkleBarkod", dt.SerializeChanges(), str);
                        gridView2.AddSummary("Qty");
                        gridView2.FormatAsNumber(0, "Qty");
                        SetProgress(gridView2.Columns["Score"]);
                        gridView2.BestFitColumns();

                        xtraTabControl1.SelectedTabPage = tpBarkodluListe;
                        //using (BarkodEkle be = new BarkodEkle(dt, Message))
                        //    be.ShowDialog();
                    }
                }
        }


        void SetProgress(GridColumn col)
        {
            //col.Caption = col.Caption.Replace("Pct", " %");
            col.ColumnEdit = new RepositoryItemProgressBar();
            ((RepositoryItemProgressBar)col.ColumnEdit).ShowTitle = true;
            ((RepositoryItemProgressBar)col.ColumnEdit).PercentView = true;
            ((RepositoryItemProgressBar)col.ColumnEdit).Maximum = 100;
        }


        public DataTable ReadExcel(string filename)
        {
            return null;
            //TODO: sadece ben görüyormuşum. başkasının ihtiyacı olduğunda SPGear'ı buraya implemente et!
            /*
            if (filename.EndsWith(".xls"))
            {
                ShowMessage("Lütfen dosyayı XLSX formatında kaydedin");
                return null;
            }

            bool hasHeader = false;
            DataTable table = new DataTable("x");
            using (var excelFile = new OfficeOpenXml.ExcelPackage())
            {
                using (var stream = File.OpenRead(filename))
                {
                    excelFile.Load(stream);
                }
                //DataSet ds = new DataSet("x");

                foreach (ExcelWorksheet ws in excelFile.Workbook.Worksheets)
                {
                    //table.TableName = ws.Name;
                    if (ws.Name.ToLower() == "export")
                    {
                        for (int i = 0; i < ws.Dimension.End.Column; i++)
                            table.Columns.Add(string.Format("Column {0}", i));


                        var startRow = hasHeader ? 2 : 1;
                        for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
                        {
                            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
                            bool ok = true;
                            foreach (var cell in wsRow)
                            {
                                for (int i = 0; i < cell.Text.Length; i++)
                                    ok &= (cell.Text.Substring(i, 1).ToInt(-1) > -1);

                                break;
                            }
                            if (!ok)
                                continue;

                            var row = table.NewRow();
                            foreach (var cell in wsRow)
                                row[cell.Start.Column - 1] = cell.Text;

                            table.Rows.Add(row);
                        }
                        //ds.Tables.Add(table);
                    }
                }
            }
            return table;
             */
        }




        private void gv_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.Column.FieldName.Length == 3 &&
                    e.Column.FieldName.StartsWith("A"))
                {
                    DataRow dr = gridView1.GetDataRow(e.RowHandle);
                    int D = intParse(dr["DagilimId"]);

                    e.Appearance.ForeColor = (DagilimId != D ? Color.LightSlateGray : Color.Black);
                }
        }

        private void Orders_Closed(object sender, EventArgs e)
        {
            DagilimId = (sender as BaseEdit).EditValue.ToInt(-1);
            DagilimChanged();
        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            DagilimId = bsOrders.GetCurrentValue("DagilimId").ToInt(-1);
            DagilimChanged();
        }

        private void DagilimChanged()
        {
            try
            {
                gridView1.CloseEditor();
                gridView1.BeginUpdate();

                MyData.DagilimRow r = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId);
                if (r != null)
                    for (int i = 1; i < 29; i++)
                    {
                        string fieldName = String.Format("A{0:00}", i);
                        string cap = r[String.Format("A{0:00}", i)].ToString();
                        gridView1.Columns[fieldName].Caption = cap != string.Empty ? cap : " ";
                    }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                gridView1.EndUpdate();
            }
        }


    }
}
